package com.zmj.ascept;

import com.zmj.entity.Log;
import com.zmj.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class LogAspect {

   @Autowired
    LogService logService;

    @Pointcut("execution(* com.zmj.service.UserInfoService.add*(..))||execution(* com.zmj.service.UserInfoService.del*(..))||execution(* com.zmj.service.UserInfoService.update*(..))")
    public void addLog(){
    }


    @AfterReturning("addLog()")
    public void add(JoinPoint joinPoint){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        Log l=new Log();
        String classname=joinPoint.getSignature().toString();
        String method=joinPoint.getSignature().getName();
       /* if (method.contains("sel")){
            l.setDescription("用户管理-查找");
        }*/
        if (method.contains("del")){
            l.setDescription("用户管理-删除");
        }
        if (method.contains("add")){
            l.setDescription("用户管理-新增");
        }
        if (method.contains("update")){
            l.setDescription("用户管理-修改");
        }
        log.info(classname);
        l.setClassAndMethod(classname);
        Object[] args = joinPoint.getArgs();
        String s= Arrays.toString(args);
        if(s==null||s.equals("")){
            l.setDatas("无");
        }else {
            l.setDatas(s);
        }
        l.setUpdateTime(new Date());
        String ip = request.getRemoteAddr();
        System.out.println(ip);
        l.setIpPath(ip);
        String path = request.getRequestURL().toString();
        l.setIpUrl(path);
        l.setRemark("朱明洁操作的");
        logService.addLogger(l);
    }
}
